package com.ttg.web.service.job.impl;

import com.google.common.collect.Lists;
import com.google.common.util.concurrent.ListenableFuture;
import com.ttg.common.annotation.TaskRunMethod;
import com.ttg.common.enums.DimTypeEnum;
import com.ttg.common.enums.LadderRuleTypeEnum;
import com.ttg.common.exception.BaseException;
import com.ttg.common.vo.TaskResultVO;
import com.ttg.model.dto.QualityManageReportDTO;
import com.ttg.common.dto.TaskBaseDTO;
import com.ttg.model.dto.job.MerchScoreDTO;
import com.ttg.model.pojo.ModelMctMonth;
import com.ttg.model.pojo.QualityManageLadderRule;
import com.ttg.model.pojo.QualityManageMerchReport;
import com.ttg.web.dao.*;
import com.ttg.web.juc.TasktemplateHelper;
import com.ttg.web.service.job.QualityManageCommon;
import com.ttg.web.service.job.MerchScoreJobService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * Description：
 * Author: chenyou
 * Date: 2025/9/1 15:55
 * Company: ttg
 * Copyright: Copyright (c) 2025
 */
@Slf4j
@Service
@TaskRunMethod(value = "merchScoreTask")
public class MerchScoreJobServiceImpl extends QualityManageCommon implements MerchScoreJobService {

    @Value("${tlinx.isJuc:false}")
    private volatile Boolean isJuc;//是否启用异步回调
    @Autowired
    private TasktemplateHelper tasktemplateHelper;
    @Autowired
    private QualityManageMerchReportDao merchReportDao;
    @Autowired
    private QualityManageLadderRuleDao ladderRuleDao;
    @Autowired
    private QualityManageWeightConfigDao weightConfigDao;
    @Autowired
    private IndustryInfoDao industryInfoDao;
    @Autowired
    private ModelMctMonthDao modelMctMonthDao;

    /**
     * 商户活跃率，清算成本，存款归集，加权得分计算
     */
    @Override
    public TaskResultVO merchScore(TaskBaseDTO reqDto) {
        reqDto = getCheckYearAndMonth(reqDto);
        //基于商户模型数据计算商户活跃率，清算成本，存款归集，加权得分
        List<Long> mctNoList = modelMctMonthDao.getMctNoList(reqDto.getYear(), reqDto.getMonth());
        List<List<Long>> mctNoPartList = Lists.partition(mctNoList,500);

        //删除旧数据
        merchReportDao.deleteByMonth(reqDto.getYear(), reqDto.getMonth());

        List<QualityManageLadderRule> rules = ladderRuleDao.getByDimType(DimTypeEnum.商户维度.getValue());
        if(rules==null){
            throw new BaseException("商户阶梯评价规则不能为空");
        }
        List<ListenableFuture<TaskResultVO>> futures = new ArrayList<>();
        List<TaskResultVO> results = new ArrayList<>();
        for(List<Long> mctNoPart : mctNoPartList){
            MerchScoreDTO merchScoreDTO = new MerchScoreDTO();
            merchScoreDTO.setMctNos(mctNoPart);
            merchScoreDTO.setLadderRules(rules);
            if(isJuc){
                futures.add(tasktemplateHelper.submit(this,reqDto,merchScoreDTO));
            }else {
                TaskResultVO result = merchScoreTask(reqDto,merchScoreDTO);
                results.add(result);
            }
        }
        return taskResult(results,futures,isJuc);
    }

    /**
     * 可异步处理的逻辑
     */
    public TaskResultVO merchScoreTask(TaskBaseDTO reqDto, MerchScoreDTO merchScoreDTO){
        try {
            List<Long> mctNos = merchScoreDTO.getMctNos();
            List<ModelMctMonth> modelMctMonths = modelMctMonthDao.getByMctNos(reqDto.getYear(),reqDto.getMonth(),mctNos);
            List<QualityManageMerchReport> merchReports = new ArrayList<>();
            for(ModelMctMonth merchInfo: modelMctMonths){
                QualityManageMerchReport report = new QualityManageMerchReport();
                List<QualityManageLadderRule> rules = merchScoreDTO.getLadderRules();
                //商户活跃天数得分
                merchLivenessDayScore(merchInfo, report, rules);
                //商户清算成本得分
                merchClearCostScore(merchInfo, report, rules);
                //商户存款归集得分
                merchAvgScore(merchInfo, report, rules);
                //加权得分
                QualityManageReportDTO reportDTO = new QualityManageReportDTO();
                BeanUtils.copyProperties(report, reportDTO);
                reportDTO = weightScore(reportDTO, DimTypeEnum.商户维度.getValue());
                report.setRepWeightScore(reportDTO.getRepWeightScore());

                report.setRepMctNo(merchInfo.getMctNo().toString());
                report.setRepMctName(merchInfo.getMctName());
                report.setRepMctCustNo(merchInfo.getMctCustNo());
                report.setRepYear(reqDto.getYear());
                report.setRepMonth(reqDto.getMonth());
                report.setRepClsId1(merchInfo.getClsId1());
                report.setRepClsId2(merchInfo.getClsId2());

                merchReports.add(report);
            }
            //保存
            merchReportDao.saveBatch(merchReports);
//            merchReportDao.efficientBatchSaveOrUpdate(merchReports);

        }catch (BaseException e) {
            e.printStackTrace();
            return taskReuslt(Status.FAIL.getValue(),false, e.getMsg());
        }catch (Exception ex){
            ex.printStackTrace();
            String exType = ex.getClass().getSimpleName();
            return taskReuslt(Status.FAIL.getValue(),false,"异常类型：" + exType + ",异常信息：" + ex.getMessage());
        }
        return taskReuslt(Status.SUCCESS.getValue(),false,"ok");
    }

    /**
     * 商户活跃天数得分
     * 活跃天数 = 当前商户在收单平台的月活跃天数
     */
    public void merchLivenessDayScore(ModelMctMonth merchInfo, QualityManageMerchReport report, List<QualityManageLadderRule> rules){
        //todo 数据来源 ：
        // 1.收单平台同步所有商户的月活跃天数
        //1. 查询商户月活跃天数
        Integer livenessDay = merchInfo.getLivenessDays();
        report.setRepLivenessDay(livenessDay);
        //2. 匹配商户活跃率阶梯规则得分
        BigDecimal ruleScore = getRuleScore(LadderRuleTypeEnum.商户活跃天数.getValue(),new BigDecimal(livenessDay),rules);
        report.setRepLivenessScore(ruleScore);
    }

    /**
     * 商户清算成本得分
     * 清算成本 = 对应商户的补贴额之和/商户的年日均存款
     */
    public void merchClearCostScore(ModelMctMonth merchInfo, QualityManageMerchReport report, List<QualityManageLadderRule> rules){
        //todo 数据来源：
        // 1.收单平台同步所有商户的补贴额
        // 2.行方数据仓库同步商户结算账户的年日均存款
        //1. 计算商户清算成本
        BigDecimal clearCost = merchInfo.getClearCost();
        report.setRepClearCost(clearCost);
        //2. 匹配商户清算成本阶梯规则得分
        BigDecimal ruleScore =  getRuleScore(LadderRuleTypeEnum.清算成本.getValue(),clearCost,rules);
        report.setRepClearCostScore(ruleScore);
    }

    /**
     * 商户存款归集得分
     * 户均归集 = 对应商户的年日均存款额
     */
    public void merchAvgScore(ModelMctMonth merchInfo, QualityManageMerchReport report, List<QualityManageLadderRule> rules){
        //todo 数据来源：
        // 1.行方数据仓库同步商户结算账户的年日均存款，执行任务时按要求计算平均数
        //1. 计算行业户均归集存款额
        BigDecimal avg = merchInfo.getAvgDepositAmt();
        report.setRepAvg(avg);
        //2. 匹配行业户均归集阶梯规则得分
        BigDecimal ruleScore =  getRuleScore(LadderRuleTypeEnum.户均归集.getValue(),avg,rules);
        report.setRepAvgScore(ruleScore);
    }
}
